package com.yz.food.controller;

import com.yz.food.common.Const;
import com.yz.food.common.ServerResponse;
import com.yz.food.pojo.Cart;
import com.yz.food.pojo.Category;
import com.yz.food.pojo.Order;
import com.yz.food.pojo.User;
import com.yz.food.service.CartService;
import com.yz.food.service.CategoryService;
import com.yz.food.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CartService cartService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 跳转到购物车界面
     *
     * @return
     */
    @RequestMapping("page/checkout")
    public String checkout(HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return "loginOrRegister";
        }
        // 查询出购物车商品
        List<Cart> carts = cartService.getByEmail(user.getEmail());
        modelMap.addAttribute("carts", carts);
        modelMap.addAttribute("totalPrice", totalPrice(carts));
        List<Category> categories = categoryService.getAll();
        modelMap.addAttribute("categories", categories);
        return "checkout";
    }

    /**
     * 把购物车内容写进订单
     */
    @RequestMapping(value = "order/addOrder", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse addOrder(HttpServletRequest request, Order order) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("下单失败");
        }
        int result = orderService.addOrder(order, user.getEmail());
        if (result > 0) {
           return ServerResponse.createBySuccessMessage("下单成功");
        }
        return ServerResponse.createByErrorMessage("下单失败");
    }

    // 计算总价格
    private double totalPrice(List<Cart> list) {
        double price = 0.0;
        for (Cart cart : list) {
            price += price + cart.getTotalPrice();
        }
        return price;
    }

}
